const { runCmd } = require("../utils/run-cmd");
const { errorTypes } = require("../error/error-types");
const config = require("../app/config");
const { sendMsg } = require("../utils/send");

class WebHooksController {
  async handleWebHooks(ctx, next) {

    let upAndDeploy = (ctx, suffix) => {
      let repositoryName = ctx.request.body._repositoryName;
      console.log('仓库名：', repositoryName)
      repositoryName = repositoryName.replace(/-/g, '_')
      const shellIsExist = config.shellNames.includes(repositoryName);
      const workPath = config.workPathMap[repositoryName];
      if (!shellIsExist) ctx.emitError(errorTypes.NO_EXECUTION_FILE);
      if (!workPath) ctx.emitError(errorTypes.WORK_PATH_NOT_EXIST)
      runCmd(
        "sh",
        [`${config.libPath}/${repositoryName}${suffix}.sh`, workPath],
        {
          cwd: workPath,
        },
        () => {
          console.log(`[${repositoryName}] 任务执行结束!`);
        },
      );
    }

    const data = ctx.request.body;

    upAndDeploy(ctx, '')

    let title = ''
    console.log(data)

    if (data.hook_name === 'push_hooks') {
      title = '代码提交'
      sendMsg(data, config, 'commit', title);

      if (data.ref === 'refs/heads/master') {
        upAndDeploy(ctx, '_deploy')
      }

    } else if (data.hook_name === 'issue_hooks') {

    } else if (data.hook_name === 'merge_request_hooks') {

      if (data.action === 'open') {
        title = '合并分支'
      }

      if (data.action === 'merge') {
        title = '完成分支合并'
      }

      if (data.action_desc === 'check_pass') {
        title = '审查通过'
      }

      if (data.action_desc === 'test_pass') {
        title = '测试通过'
      }

      sendMsg(data, config, 'pr', title)

    } else if (data.hook_name === 'note_hooks') {

    }

    ctx.body = {
      code: 200,
      message: "回调成功",
    };
  }
}

module.exports = new WebHooksController();
